from flask import g
from typing import Union
from flask import request
from public.local import datetime_type
from security.security import encode_jwt
from security.security import decode_jwt
from sqlalchemy import text


def context_logs(name: str, obsolescence: Union[str, None], data: Union[str, None]) -> bool:
    change: bool = True
    option: dict = {
        "POST": "添加",
        "PUT": "更新",
        "DELETE": "删除"
    }
    create: Union[str, None] = None
    # noinspection PyBroadException
    try:
        if g.token is not None:
            user_id: int = decode_jwt(g.token)["user_id"]
            sql_context = "SELECT name FROM users WHERE id = :user_id"
            create, = g.session.execute(text(sql_context), {"user_id": user_id}).fetchone()
    except Exception as e:
        change = False
    path = request.path
    method = option.get(request.method)

    sql_context = """
    INSERT INTO logs(
        route, "method", "name", "user", obsolescence, "data", "time"
    ) VALUES (:route, :method, :name, :user, :obsolescence, :data, :time)
    """
    parm: dict = {
        "route": path,
        "method": method,
        "name": name,
        "user": create,
        "obsolescence": obsolescence,
        "data": data,
        "time": datetime_type()
    }
    g.session.execute(text(sql_context), parm)
    g.session.commit()
    return change
